﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using S7.Net;

namespace thinger.HeatingControlProject
{
    /// <summary>
    /// S7通讯库二次封装类
    /// </summary>
    public class S7NetLib
    {
        private Plc s7netlib = null;

        public CpuType CPUType { get; set; }
        public string IPAddress { get; set; }
        public short Rack { get; set; }
        public short Slot { get; set; }

        public S7NetLib(CpuType type, string ip, short rack, short slot)
        { 
            this.CPUType = type;
            this.IPAddress = ip;
            this.Rack = rack;
            this.Slot = slot;
        }
        /// <summary>
        /// 打开PLC连接
        /// </summary>
        public void OpenPLC()
        {
            if (s7netlib == null)
            {
                s7netlib = new Plc(CPUType, IPAddress, Rack, Slot);

            }
            if(!this.s7netlib.IsConnected)
            {
                s7netlib.ReadTimeout = 1000;
                s7netlib.WriteTimeout = 1000;
                s7netlib.Open();
            }
        }

        /// <summary>
        /// 关闭PLC连接
        /// </summary>
        public void ClosePLC()
        {
            if(this.s7netlib != null && this.s7netlib.IsConnected)
            {
                this.s7netlib.Close();
            }
        }
        /// <summary>
        /// 给PLC单个变量写入数据
        /// </summary>
        /// <param name="varAddress"></param>
        /// <param name="varValue"></param>
        public void WriteDataToPLC(string varAddress,object varValue)
        {
            OpenPLC();
            lock (this)
            {
                this.s7netlib.Write(varAddress, varValue);
            }
        }
        /// <summary>
        /// PCL批量读取数据
        /// </summary>
        /// <param name="dataType"></param>
        /// <param name="db"></param>
        /// <param name="startByteAdr"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public byte[] ReadDataFromPLC(DataType dataType,int db,int startByteAdr,int count)
        {
            OpenPLC();
            lock (this)
            {
                byte[] result = this.s7netlib.ReadBytes(dataType, db, startByteAdr, count);
                return result;
            }
        }
    }
}
